package com.hand.wfive.view;

import android.graphics.Bitmap;
import android.graphics.Matrix;

import androidx.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;

import java.security.MessageDigest;

public class SizeTransformation extends BitmapTransformation {

    private static final String ID = "com.hand.wfive.view.SizeTransformation";
    private static final byte[] ID_BYTES = ID.getBytes(CHARSET);

    private final long mMaxSize;

    public SizeTransformation(long size) {
        mMaxSize = size;
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        if (Math.max(outWidth, outHeight) > mMaxSize) {
            Matrix matrix = new Matrix();
            float scale = mMaxSize * 1f / Math.max(outWidth, outHeight);
            matrix.setScale(scale, scale);
            return Bitmap.createBitmap(toTransform, 0, 0, outWidth, outHeight, matrix, true);
        }
        return toTransform;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof CenterCrop;
    }

    @Override
    public int hashCode() {
        return ID.hashCode();
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        messageDigest.update(ID_BYTES);
    }
}
